directives.directive('tablesConnect', ["$rootScope", "tools","$timeout", function ($rootScope, tools,$timeout) {
    return {
        restrict: 'AE',
        scope: {},
        replace: true,
        templateUrl: "/trend-new-BI/app/components/dbManager/tableConnect/tableConnectView.html",
        link: function (scope, element, attr) {
            scope.table1 = {}; //表1
            scope.table2 = {}; //表2
            //scope.joinType = null; //关联的类型
            scope.joinType = 'leftJoin';
            scope.msg = null;
            //下拉框的个数--字段的关联--init
            scope.dataSum = [0];

            //存储选择的字段关联的信息---init
            scope.dataFileds = [{}];

            /**
             * 获取字段
             * @param tbId
             * @param tableType
             * @param index  第几个表 表1 or 表2
             */
            function getFiled(tbId, tableType, index) {
                tools.get({
                    method: 'POST',
                    url: '/Ibm-Client/getSingleTable.htm',
                    data: {
                        tbId: tbId,
                        tableType:tableType
                    },
                    succ: function (resp) {
                        if (resp.success) {

                            if (index == 1) {
                                scope.table1.filed = resp.value.columns;
                                for(var i in scope.table1.filed){
                                    scope.table1.filed[i].isSelected = false;
                                }
                           //     console.log("字段");
                            //    console.log(scope.table1.filed);
                            } else {
                                scope.table2.filed = resp.value.columns;
                                for(var i in scope.table2.filed){
                                    scope.table2.filed[i].isSelected = false;
                                }
                              //  console.log("字段");
                              //  console.log(scope.table2.filed);
                            }

                        }else{
//                            alert(resp.message);
                            $timeout(function(){
                                $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                                return;
                            },500);
                        }
                    }
                });
            }

            $rootScope.$on('Show_tableConnect_EV', function (e, data) {
//                $('.test.checkbox').checkbox('attach events', '.uncheck.button', 'uncheck');
                $(".leftTableR .checkbox.selectTable").checkbox('attach events', '.uncheck.button', 'uncheck');
                $(".rightTableR .checkbox.selectTable").checkbox('attach events', '.uncheck.button', 'uncheck');
                $('.uncheck.button').click();
                $timeout(function(){
                    $(element).modal('show');
                },500);

                if(scope.table1.value!=null && scope.table2.value!=null){
                    if(scope.table1.value.tbId == data[0].tbId && scope.table2.value.tbId == data[1].tbId){
                        return
                    }
                }
                scope.table1.value = data[0];
                scope.table2.value = data[1];

                getFiled(scope.table1.value.tbId, scope.table1.value.tableType, 1);
                getFiled(scope.table2.value.tbId, scope.table2.value.tableType, 2);

                scope.msg = null;
            });
            $rootScope.$on("Saved_it_EV",function(){
                scope.table1 = {}; //表1
                scope.table2 = {}; //表2
                //下拉框的个数--字段的关联--init
                scope.dataSum = [0];

                //存储选择的字段关联的信息---init
                scope.dataFileds = [{}];
                scope.joinType = 'leftJoin';
            });
            //显示隐藏的字段
            $("#connect .leftTableR .checkbox.selectTable").checkbox({
                onChecked: function() {
                   // console.log("11211");
                    $timeout(function(){
                        for(var i in scope.table1.filed){
                            scope.table1.filed[i].isSelected = true;
                        }
                    },10);

//                    console.log("left checked");
                    //scope.$apply();
                },
                onUnchecked: function() {
                    $timeout(function(){
                        for(var i in scope.table1.filed){
                            scope.table1.filed[i].isSelected = false;
                        }
                    },10);

                   // scope.$apply();
                }
            });
            $("#connect .rightTableR .checkbox.selectTable").checkbox({
                onChecked: function() {
                    $timeout(function () {
                        for(var i in scope.table2.filed){
                            scope.table2.filed[i].isSelected = true;
                        }
                    },10);

                    //scope.$apply();
                },
                onUnchecked: function() {
                    $timeout(function(){
                        for(var i in scope.table2.filed){
                            scope.table2.filed[i].isSelected = false;
                        }
                    },10);

                    //scope.$apply();
                }
            });
            /*//选择表的关联关系--左关联，右。。
            scope.tableJoin = function (event, joinType) {
               *//* var $tar = $(event.target);
                if ($tar.hasClass('active')) {
                    scope.joinType = '';
                    return;
                }
                $tar.addClass('active').siblings().removeClass('active');*//*
                //关联名称
                scope.joinType = joinType;
                //scope.dataFileds = [{}];
                //scope.dataSum = [0];
            };*/

            //取消创建关联
            scope.cancel = function () {
                scope.msg = null;
                $(element).modal('hide');
            };

            //增加字段
            scope.addSum = function () {
                scope.dataFileds.push({});
                scope.dataSum.push(scope.dataSum.length);
               // console.log(scope.dataFileds);
            };

            //删除字段
            scope.lessSum = function (index) {
                if(scope.dataSum.length==1){
                    return;
                }
                scope.dataSum.splice(index, 1);
                scope.dataFileds.splice(index, 1);
            };

            //创建
            scope.ok = function () {
                //表的关联连接没有选择
                if (scope.joinType == null) {
                    scope.msg = '请选择表的关联类型';
                    $timeout(function(){
                        scope.msg = null;
                    },2000);
                    return;
                }
                //关联的字段没有选择
                var selectBoolean = true;
                angular.forEach(scope.dataFileds, function (item) {
                    if (item.left == null || item.right == null) {
                        scope.msg = '请选择表的关联字段';
                        selectBoolean = false;
                        return;
                    }
                });
                if (!selectBoolean) {
                    $timeout(function(){
                        scope.msg = null;
                    },2000);
                    return;
                }
                //关联的字段重复多次关联
                var selectDouble = true;
                for(var i=0;i<scope.dataFileds.length;i++){
                    for(var j=i+1;j<scope.dataFileds.length;j++){
                        if((scope.dataFileds[i].left ==scope.dataFileds[j].left) && (scope.dataFileds[i].right ==scope.dataFileds[j].right)){
                            scope.msg = '该关联字段已存在，请删除后再操作';
                            selectDouble =false;
                            return;
                        }
                    }
                }
                if(!selectDouble){
                    $timeout(function(){
                        scope.msg = null;
                    },2000);
                    return;
                }
                //字段要放在关联里显示
                var leftTable = false;
                angular.forEach(scope.table1.filed,function(item){
                    if(item.isSelected){
                        leftTable = true;
                    }
                });
                if(!leftTable){
                    scope.msg = "请勾选左表要显示的字段"
                    $timeout(function(){
                        scope.msg = null;
                    },2000);
                    return;
                }
                var rightTable = false;
                angular.forEach(scope.table2.filed,function(item){
                    if(item.isSelected){
                        rightTable = true;
                    }
                });
                if(!rightTable){
                    scope.msg = "请勾选右表要显示的字段"
                    $timeout(function(){
                        scope.msg = null;
                    },2000);
                    return;
                }


//loading
                $rootScope.$broadcast("loading_Start_EV");

                //所有的字段选择信息----scope.dataFileds--从table中获取相应的值
                angular.forEach(scope.dataFileds, function (item) {//数组json
                    angular.forEach(scope.table1.filed, function (itemleft) {//table1
                        if (item.left == itemleft.columnDesc) {
                            item.leftData = {};
                            item.leftData.columnType = itemleft.columnType;
                            item.leftData.columnId = itemleft.columnId;
                            item.leftData.fieldName = itemleft.fieldName;
                            return;
                        }
                    });
                    angular.forEach(scope.table2.filed, function (itemright) {//table2
                        if (item.right == itemright.columnDesc) {
                            item.rightData = {};
                            item.rightData.columnType = itemright.columnType;
                            item.rightData.columnId = itemright.columnId;
                            item.rightData.fieldName = itemright.fieldName;
                            return;
                        }
                    });
                });

                //数据
                var json = {};
                json.leftColumnIds = '';
                json.rightColumnIds = '';
                json.relationColumnIds = '';
                json.relationColumnFields = '';
                json.leftColumnsDesc = '';
                json.rightColumnsDesc = '';
                json.leftColumnsType = '';
                json.rightColumnsType = '';
                json.leftColumnFieldNames = '';
                json.rightColumnFieldNames = '';



                //json.tableName = data;
                json.relationType = scope.joinType;
                json.leftTableType = scope.table1.value.tableType;
                json.rightTableType = scope.table2.value.tableType;
                json.leftTableId = scope.table1.value.tbId;
                json.rightTableId = scope.table2.value.tbId;
                //显示字段filedName
                angular.forEach(scope.table1.filed, function (item) {
                    if(item.isSelected){
                        json.leftColumnFieldNames += item.fieldName + ',';
                        json.leftColumnIds += item.columnId + ',';
                        json.leftColumnsType += item.columnType + ',';
                        json.leftColumnsDesc += item.columnDesc + ',';
                    }

                });
                angular.forEach(scope.table2.filed, function (item) {
                    if(item.isSelected){
                        json.rightColumnFieldNames += item.fieldName + ',';
                        json.rightColumnIds += item.columnId + ',';
                        json.rightColumnsType += item.columnType + ',';
                        json.rightColumnsDesc += item.columnDesc + ',';
                    }

                });

                //关联的columniIds
                angular.forEach(scope.dataFileds, function (item) {
                    json.relationColumnIds += item.leftData.columnId + '=' + item.rightData.columnId + ',';
                    json.relationColumnFields += item.leftData.fieldName + '=' + item.rightData.fieldName + ',';
                });
                $(element).modal('hide');
                $rootScope.$broadcast('IbmRelationTable_EV', json, scope.joinType);


            };
        }
    };
}]);